#!/usr/bin/env python
'''
A script for sending emails using Mandrill that is compatible with the sendmail binary interface
'''
import mandrill, sys

emails = []
require_emails = True
stop_on_dot = True
from_email = None
from_name = None

# We only support a few options - -f, -r, -F, -i, -oi, and -t, and sendmail uses custom option formats, so let's do a custom parser
ignore_params = ['-h', '-C', '-B', '-L', '-N', '-A', '-O', '-R', '-q', '-qI', '-qR', '-qS', '-V', '-X']
argv = sys.argv[1:]
while len(argv) > 0:
    arg = argv.pop(0)
    if arg == '-i' or arg == '-oi':
        stop_on_dot = False
    elif arg == '-t':
        require_emails = False
    elif arg == '-f' or arg == '-r':
        from_email = argv.pop(0)
    elif arg == '-F':
        from_name = argv.pop(0)
    elif arg == '--':
        emails.extend(argv)
        argv = []
    elif arg == '-o':
        #-o takes two arguments, so ignore them both
        argv.pop(0)
        argv.pop(0)
    elif arg[0] in ignore_params:
        #If it's an ignored option that tags an argument, ignore the argument too
        argv.pop(0)
    elif arg[0] == '-':
        #All other arguments are also ignored
        pass
    else:
        emails.append(arg)

if require_emails and len(emails) == 0:
    print 'No recipients specified'
    sys.exit(2)
elif not require_emails and len(emails) == 0:
    emails = None

if stop_on_dot:
    lines = []
    for line in sys.stdin:
        if line == '.\n':
            break
        else:
            lines.append(line)
    raw_msg = ''.join(lines)
else:
    raw_msg = sys.stdin.read()

m = mandrill.Mandrill()
m.messages.send_raw(raw_msg, from_email, from_name, emails)
